﻿using CommonBase;
using CommonClass;
using DataLib;
using EnvCommonUtility;
using EnvControlLib;
using FileLib;
using InteractiveWhiteboardManagement.Base.Common;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.Prism.Regions;
using Microsoft.Practices.Prism.ViewModel;
using Microsoft.Practices.ServiceLocation;
using SurveillanceLib;
using SurveillancePro.Base.Common;
using SurveillancePro.Base.Events;
using SurveillancePro.Base.ViewModels;
using SurveillancePro.Views;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace SurveillancePro.ViewModels
{
    /// <summary>
    /// 主界面
    /// </summary>
    public class ViewModel_Shell : WorkspaceViewModel
    {
        #region Private Fields

        private List<EnvVideoPanel> _panelNewCurrentList = null; // 记录最新的分屏列表
        private Accordion _navigationPanel; // 导航面板
        private Panel _splitPanel; // 画面分割区
        private EnvVideoPanel _maxScreenPanel; // 最大化视频窗口
        private EnvPanelOperation _panelOperation = new EnvPanelOperation();

        private readonly IServiceLocator _serviceLocator;
        private readonly IModuleManager _moduleManager;
        private readonly IModuleCatalog _moduleCatalog;
        private readonly IRegionManager _regionManager;
        private readonly IEventAggregator _eventAggregator;

        #endregion

        #region Constructor

        public ViewModel_Shell(IServiceLocator serviceLocator,
            IModuleManager moduleManager, IModuleCatalog moduleCatalog,
            IRegionManager regionManager, IEventAggregator eventAggregator)
        {
            base.BaseRegionManager = regionManager;
            EnvUtilities.EnvServiceLocator = this._serviceLocator = serviceLocator;
            EnvUtilities.EnvModuleManager = this._moduleManager = moduleManager;
            EnvUtilities.EnvModuleCatalog = this._moduleCatalog = moduleCatalog;
            EnvUtilities.EnvRegionManager = this._regionManager = regionManager;
            EnvUtilities.EnvEventAggregator = this._eventAggregator = eventAggregator;

            #region 系统初始化操作
            try
            {
                Utilities.DatabaseName = "db_ISS";
                Utilities.ChangeDBFileAccessControl(Utilities.DatabaseName); // 增加 mdb 文件修改权限
                _initializeINIFile(); // 初始化 ini 文件
                Utilities.BackupDatabase("BackupDirectory", Utilities.DatabaseName); // 自动备份数据库
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }

            #region 模块加载
            _changeIndicatorState(true);
            // 模块加载完全时，才能做下一步操作！
            moduleManager.LoadModuleCompleted += (s, e) =>
            {
                _changeIndicatorState(false);
            };
            #endregion

            #region 模块间通信
            // 所有子模块操作后的主模块入口，回到主模块执行操作(ViewModel_SplitScreen | ViewModel_DeviceTree)
            OpenModelEvent openEvent = _eventAggregator.GetEvent<OpenModelEvent>();
            openEvent.Subscribe(_manageData, ThreadOption.UIThread, true,
                x => x.ModelName == this.GetType().Name);
            #endregion
            #endregion

            #region 注册并显示视频页面容器
            this._regionManager.RegisterViewWithRegion(RegionNames.ContentRegion,
                typeof(View_VideoPanel)); // 注册视图页面容器
            this._regionManager.RequestNavigate(RegionNames.ContentRegion,
                ViewNames.SurveillancePro_VideoPanel); // 显示视频页面容器
            #endregion

            try
            {
                #region 生成机器码
                Utilities.GenerateMachineCode();
                #endregion
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }
        }

        #endregion

        #region Base Class Overrides

        protected override void OnDispose()
        {
            _dispose();
        }

        #endregion

        #region Property

        /// <summary>
        /// 是否显示 进度条
        /// </summary>
        public bool Indicator_IsBusy { get; private set; }

        #endregion

        #region Private Methods

        /// <summary>
        /// 释放资源
        /// </summary>
        private void _dispose()
        {
            base.CloseWorkspaceTabs(); // 关闭所有 Tab
        }

        /// <summary>
        /// 修改 进度条 状态
        /// </summary>
        /// <param name="state"></param>
        private void _changeIndicatorState(bool state)
        {
            Indicator_IsBusy = state;
            base.OnPropertyChanged("Indicator_IsBusy");
        }

        /// <summary>
        /// 初始化 ini 文件
        /// </summary>
        private void _initializeINIFile()
        {
            // ini 文件 初始化
            bool isOK = true; // 表示 ini 文件中的值是正常的
            INIOperation iniOperation = new INIOperation();
            string iniPath = string.Format(@"{0}\{1}\{2}.ini", Environment.CurrentDirectory,
                "DataBase", Utilities.DatabaseName);

            // ini 文件 获取值
            int outValueLength; // ini 键值字符串长度
            string iniDownloadVideoPath = iniOperation.ReadValue(SurveillanceUtilities.INI_SECTIONNAME_USERCONFIG,
                SurveillanceUtilities.INI_KEYNAME_USERCONFIG_DOWNLOADVIDEOPATH,
                iniPath, out outValueLength); // 读 ini 文件中录像文件下载路径
            string iniRecordVideoPath = iniOperation.ReadValue(SurveillanceUtilities.INI_SECTIONNAME_USERCONFIG,
                SurveillanceUtilities.INI_KEYNAME_USERCONFIG_RECORDVIDEOPATH,
                iniPath, out outValueLength); // 读 ini 文件中录像路径
            string iniConvertVideoPath = iniOperation.ReadValue(SurveillanceUtilities.INI_SECTIONNAME_USERCONFIG,
                SurveillanceUtilities.INI_KEYNAME_USERCONFIG_CONVERTVIDEOPATH,
                iniPath, out outValueLength); // 读 ini 文件中转换路径
            string iniScreenShotPath = iniOperation.ReadValue(SurveillanceUtilities.INI_SECTIONNAME_USERCONFIG,
                SurveillanceUtilities.INI_KEYNAME_USERCONFIG_SCREENSHOTPATH,
                iniPath, out outValueLength); // 读 ini 文件中截图路径

            // 判断路径合法性
            #region 判断路径合法性
            DirectoryInfo directoryPath;

            try
            {
                directoryPath = new DirectoryInfo(iniDownloadVideoPath);
                if (!directoryPath.Exists) // 录像文件下载路径不存在时
                {
#if DEBUG
                    Debug.WriteLine("录像文件下载路径不存在");
#endif
                    isOK = false;
                    iniDownloadVideoPath = SurveillanceUtilities.USERCONFIG_DOWNLOADVIDEOPATH_DEFAULT;
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                isOK = false;
                iniDownloadVideoPath = SurveillanceUtilities.USERCONFIG_DOWNLOADVIDEOPATH_DEFAULT;
            }

            try
            {
                directoryPath = new DirectoryInfo(iniRecordVideoPath);
                if (!directoryPath.Exists) // 录像路径不存在时
                {
#if DEBUG
                    Debug.WriteLine("录像路径不存在");
#endif
                    isOK = false;
                    iniRecordVideoPath = SurveillanceUtilities.USERCONFIG_RECORDVIDEOPATH_DEFAULT;
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                isOK = false;
                iniRecordVideoPath = SurveillanceUtilities.USERCONFIG_RECORDVIDEOPATH_DEFAULT;
            }

            try
            {
                directoryPath = new DirectoryInfo(iniConvertVideoPath);
                if (!directoryPath.Exists) // 转换路径不存在时
                {
#if DEBUG
                    Debug.WriteLine("转换路径不存在");
#endif
                    isOK = false;
                    iniConvertVideoPath = SurveillanceUtilities.USERCONFIG_CONVERTVIDEOPATH_DEFAULT;
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                isOK = false;
                iniConvertVideoPath = SurveillanceUtilities.USERCONFIG_CONVERTVIDEOPATH_DEFAULT;
            }

            try
            {
                directoryPath = new DirectoryInfo(iniScreenShotPath);
                if (!directoryPath.Exists) // 截图路径不存在时
                {
#if DEBUG
                    Debug.WriteLine("截图路径不存在");
#endif
                    isOK = false;
                    iniScreenShotPath = SurveillanceUtilities.USERCONFIG_SCREENSHOTPATH_DEFAULT;
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                isOK = false;
                iniScreenShotPath = SurveillanceUtilities.USERCONFIG_SCREENSHOTPATH_DEFAULT;
            }
            #endregion

            // 写入全局静态变量中保存
            SurveillanceUtilities.DownloadVideoPath = iniDownloadVideoPath;
            SurveillanceUtilities.RecordVideoPath = iniRecordVideoPath;
            SurveillanceUtilities.ConvertVideoPath = iniConvertVideoPath;
            SurveillanceUtilities.ScreenShotPath = iniScreenShotPath;

            // 写对应值到 ini 文件
            if (!isOK)
            {
                iniOperation.WriteValue(SurveillanceUtilities.INI_SECTIONNAME_USERCONFIG,
                    SurveillanceUtilities.INI_KEYNAME_USERCONFIG_DOWNLOADVIDEOPATH, iniDownloadVideoPath, iniPath);
                iniOperation.WriteValue(SurveillanceUtilities.INI_SECTIONNAME_USERCONFIG,
                    SurveillanceUtilities.INI_KEYNAME_USERCONFIG_RECORDVIDEOPATH, iniRecordVideoPath, iniPath);
                iniOperation.WriteValue(SurveillanceUtilities.INI_SECTIONNAME_USERCONFIG,
                    SurveillanceUtilities.INI_KEYNAME_USERCONFIG_CONVERTVIDEOPATH, iniConvertVideoPath, iniPath);
                iniOperation.WriteValue(SurveillanceUtilities.INI_SECTIONNAME_USERCONFIG,
                    SurveillanceUtilities.INI_KEYNAME_USERCONFIG_SCREENSHOTPATH, iniScreenShotPath, iniPath);
            }
        }

        #region 导航栏
        /// <summary>
        /// 生成导航面板
        /// </summary>
        private void _generateNavigation()
        {
            if (this._moduleCatalog != null && this._moduleCatalog.Modules.Count() > 0)
            {
                //////////////////////////////////////////////////////////////////////////
                // 这里根据 App.config 动态添加导航栏
                //////////////////////////////////////////////////////////////////////////
                foreach (ModuleInfo module in this._moduleCatalog.Modules)
                {
                    switch (module.ModuleName)
                    {
                        case "DeviceMgtModule":
                            _setAccordionItem("DeviceMgt", "设备管理", module.ModuleName, ViewNames.DeviceMgtModule_DeviceTree);
                            break;
                        case "PTZControlModule":
                            _setAccordionItem("PTZControl", "云台控制", module.ModuleName, ViewNames.PTZControlModule_PTZControl);
                            break;
                        case "ScreenMgtModule":
                            _setAccordionItem("ScreenMgt", "画面选择", module.ModuleName, ViewNames.ScreenMgtModule_SplitScreen);
                            break;
                        case "ToolkitMgtModule":
                            _setAccordionItem("ToolkitMgt", "工具箱", module.ModuleName, ViewNames.ToolkitMgtModule_Toolkit);
                            break;
                        case "PersonnelLocationModule":
                            _setAccordionItem("PersonnelLocation", "人员定位", module.ModuleName, ViewNames.PersonnelLocationModule_PersonnelLocation);
                            break;


                        default:
                            break;
                    }
                }
            }
        }

        /// <summary>
        /// 设置导航分组
        /// </summary>
        /// <param name="imageName">图片名称</param>
        /// <param name="textDesc">文字描述</param>
        /// <param name="moduleName">模块名称</param>
        /// <param name="mainView">主界面</param>
        private void _setAccordionItem(string imageName,
            string textDesc, string moduleName, string mainView)
        {
            if (string.IsNullOrWhiteSpace(imageName) || string.IsNullOrWhiteSpace(textDesc) ||
                string.IsNullOrWhiteSpace(moduleName) || string.IsNullOrWhiteSpace(mainView))
            {
                return;
            }

            // 定义图片
            Image headImage = new Image();
            headImage.Height = headImage.Width = 25;
            headImage.Margin = new Thickness(5, 0, 5, 0);
            headImage.Source = new BitmapImage(new Uri(
                string.Format(ConstantString.IMAGE_URL, imageName), UriKind.RelativeOrAbsolute));

            // 定义文字
            TextBlock headText = new TextBlock();
            headText.FontSize = 20;
            headText.Margin = new Thickness(20, 0, 0, 0);
            headText.FontFamily = new System.Windows.Media.FontFamily("Microsoft YaHei");
            headText.HorizontalAlignment = HorizontalAlignment.Center;
            headText.VerticalAlignment = VerticalAlignment.Center;
            headText.Text = textDesc;

            // 定义分组
            StackPanel headPanel = new StackPanel();
            headPanel.Orientation = Orientation.Horizontal;
            headPanel.HorizontalAlignment = HorizontalAlignment.Left;
            headPanel.VerticalAlignment = VerticalAlignment.Center;
            headPanel.Children.Add(headImage);
            headPanel.Children.Add(headText);

            // 定义“组”
            AccordionItem accItem = new AccordionItem();
            accItem.Header = headPanel;
            accItem.HorizontalAlignment = accItem.HorizontalContentAlignment = HorizontalAlignment.Stretch;
            accItem.VerticalAlignment = accItem.VerticalContentAlignment = VerticalAlignment.Stretch;
            ToolTipService.SetToolTip(accItem, textDesc);
            accItem.Background = Application.Current.Resources.MergedDictionaries[0][App.Current.Resources["FormBackgroundStyle"].ToString()] as Brush;
            accItem.Style = Application.Current.Resources.MergedDictionaries[0][App.Current.Resources["AccordionItemStyle"].ToString()] as Style;
            //accItem.Selected += (s, e) =>
            //{
            //    _changeIndicatorState(true);
            //    this._moduleManager.LoadModule(moduleName); // 按需加载模块
            //};
            this._eventAggregator.GetEvent<OpenModelEvent>().Publish(new OpenModelEventArg() { ModelName = moduleName }); // 事件通知
            App.Current.Dispatcher.BeginInvoke((Action)(() =>
            {
                accItem.Content = this._serviceLocator.GetInstance<Object>(mainView); // 解析并显示界面
            }));

            this._navigationPanel.Items.Add(accItem); // 添加到导航栏
        }
        #endregion

        #region 子模块传入执行的方法
        /// <summary>
        /// 事件入口
        /// </summary>
        /// <param name="arg"></param>
        private void _manageData(OpenModelEventArg arg)
        {
            if (string.IsNullOrWhiteSpace(arg.FunctionName))
            {
#if DEBUG
                Debug.WriteLine("无效的执行操作，请输入方法名称！");
#endif
                return;
            }

            try
            {
                switch (arg.FunctionName)
                {
                    case "SplitScreen": // 画面分割操作
                        if (arg.Arg != null)
                            _splitVideoScreen(arg.Arg.ToString());
                        else
                            _splitVideoScreen("4"); // 默认 4 分屏
                        break;
                    case "SelectTreeNode": // 双击叶子结点
                        if (arg.Arg != null && arg.Arg is ITreeGroup)
                        {
                            _selectTreeNode(arg.Arg as ITreeGroup);
                        }
                        else
                        {
#if DEBUG
                            Debug.WriteLine("传入的设备树叶子结点有问题！");
#endif
                            MessageBox.Show("设备信息异常！", ConstantString.MSG_COMPANY);
                        }
                        break;



                    default:
                        break;
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
        }

        /// <summary>
        /// 画面分割
        /// </summary>
        /// <param name="splitCount">个数</param>
        private void _splitVideoScreen(string splitCount)
        {
            if (this._splitPanel == null)
                return;

            int outSplitCount;
            if (!int.TryParse(splitCount, out outSplitCount))
            {
#if DEBUG
                Debug.WriteLine("个数异常，值为：{0}", splitCount);
#endif
                outSplitCount = 4; // 默认 4 分屏
            }

            try
            {
                _panelOperation.SetNull2SelectedPanel(); // 未选中任何 Panel
                _panelNewCurrentList = _panelOperation.SplitScreen(outSplitCount, _splitPanel, _maxScreenPanel,
                    _panelNewCurrentList, null); // 画面分割
                if (_panelNewCurrentList != null && _panelNewCurrentList.Count > 0)
                {
                    EnvUtilities.ChangeBorderColor(_panelNewCurrentList[0], _panelNewCurrentList); // 高亮显示选中的视频窗口
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }
        }

        /// <summary>
        /// 双击叶子结点，播放视频
        /// </summary>
        /// <param name="selectedTreeNode"></param>
        private void _selectTreeNode(ITreeGroup selectedTreeNode)
        {
            if (_maxScreenPanel.Visibility == Visibility.Visible)
            {
                MessageBox.Show("请在视频窗口最小化时进行设置!", ConstantString.MSG_COMPANY);
                return;
            }

            int outChannel;
            if (EnvPanelOperation.SelectedPanel != null &&
                EnvPanelOperation.SelectedPanel.Tag != null &&
                EnvPanelOperation.SelectedPanel.Tag is TagModel &&
                selectedTreeNode != null &&
                selectedTreeNode.Arg != null &&
                selectedTreeNode.Arg is TagModel &&
                (selectedTreeNode.Arg as TagModel).Driver_Instance != null &&
                !string.IsNullOrWhiteSpace((selectedTreeNode.Arg as TagModel).Driver_LoginID) &&
                !string.IsNullOrWhiteSpace((selectedTreeNode.Arg as TagModel).Panel_SelectedChannel) &&
                int.TryParse((selectedTreeNode.Arg as TagModel).Panel_SelectedChannel, out outChannel))
            {
                TagModel panelTag = EnvPanelOperation.SelectedPanel.Tag as TagModel;
                TagModel treeTag = selectedTreeNode.Arg as TagModel;

                if (panelTag.Driver_Instance != null &&
                    !string.IsNullOrWhiteSpace(panelTag.Panel_RealPlayHandle))
                {
                    if (panelTag.Driver_Instance.StopRealPlay(panelTag.Panel_RealPlayHandle)) // 先停止正在播放的视频，停止实时监控，需要传递实时监控句柄
                        panelTag.Panel_RealPlayHandle = string.Empty;
                    else
                    {
                        MessageBox.Show(SurveillanceUtilities.STOP_REALPLAY_FAILURE, ConstantString.MSG_COMPANY);
                        return;
                    }
                }

                string pRealPlayHandle = treeTag.Driver_Instance.RealPlay(treeTag.Driver_LoginID,
                    outChannel, (EnvPanelOperation.SelectedPanel.DataContext as ViewModel_EnvVideoPanel).CurrentPanel.Handle); // 只取数据不播放
                treeTag.Panel_RealPlayHandle = pRealPlayHandle;
                treeTag.Panel_Index = panelTag.Panel_Index; // 记录视频窗口序号

                Utilities.CopyObject(treeTag, panelTag);
                (EnvPanelOperation.SelectedPanel.DataContext as ViewModel_EnvVideoPanel).VideoInformation =
                    selectedTreeNode.TooltipText; // 设置视频窗口文本标题信息
                _focus2NextPanel(); // 将焦点自动循环移动到下一个视频窗口中
            }
            else
            {
#if DEBUG
                Debug.WriteLine("没有选择视频窗口!");
#endif
                MessageBox.Show("没有选择视频窗口!", ConstantString.MSG_COMPANY);
            }
        }
        #endregion

        #region 视频相关
        /// <summary>
        /// 将焦点循环移动到下一个视频窗口中
        /// </summary>
        private void _focus2NextPanel()
        {
            if (_panelNewCurrentList != null &&
                EnvPanelOperation.SelectedPanel != null &&
                EnvPanelOperation.SelectedPanel.Tag != null &&
                EnvPanelOperation.SelectedPanel.Tag is TagModel &&
                (EnvPanelOperation.SelectedPanel.Tag as TagModel).Panel_Index >= 0 &&
                (EnvPanelOperation.SelectedPanel.Tag as TagModel).Panel_Index < _panelNewCurrentList.Count)
            {
                int nextPanelIndex;
                TagModel selectedPanelTag = EnvPanelOperation.SelectedPanel.Tag as TagModel;

                if (selectedPanelTag.Panel_Index + 1 >= _panelNewCurrentList.Count)
                {
                    nextPanelIndex = 0; // 回到第一个视频窗口
                }
                else
                {
                    nextPanelIndex = selectedPanelTag.Panel_Index + 1; // 下一个视频窗口
                }

                EnvUtilities.ChangeBorderColor(_panelNewCurrentList[nextPanelIndex],
                    _panelNewCurrentList); // 绘制边框
            }
        }
        #endregion

        #endregion

        #region Public Events

        /// <summary>
        /// 窗口加载时，最大化（自定义窗口时使用）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Rect rectangle = SystemParameters.WorkArea; // 获取工作区大小
            Window win = sender as Window;
            win.Left = 0;
            win.Top = 0;
            win.Width = rectangle.Width;
            win.Height = rectangle.Height;
        }

        /// <summary>
        /// 关闭窗口时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (MessageBox.Show("是否退出系统？", ConstantString.MSG_COMPANY,
                MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.OK) == MessageBoxResult.OK)
            {
                this.Dispose();

                Application.Current.Shutdown(Environment.ExitCode);
                Environment.Exit(Environment.ExitCode);
            }
            else
            {
                e.Cancel = true;
            }
        }

        /// <summary>
        /// 导航面板加载时
        /// </summary>
        /// <param name="sender">Accordion Panel</param>
        /// <param name="e"></param>
        public void Navigation_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (sender != null && sender is Accordion)
                {
                    this._navigationPanel = sender as Accordion; // 得到导航面板
                    this._navigationPanel.Items.Clear(); // 防止重复加载

                    if (this._navigationPanel.Tag != null &&
                        this._navigationPanel.Tag is TabControl &&
                        (this._navigationPanel.Tag as TabControl).Items.Count == 1 &&
                        (this._navigationPanel.Tag as TabControl).Items[0] is Panel) // 开始时只有一个页面，即：视频页面（在构造函数中已加载）
                    {
                        TabControl tab = this._navigationPanel.Tag as TabControl;
                        this._splitPanel = tab.Items[0] as Panel; // 得到视频窗口容器

                        if (tab.Tag != null && tab.Tag is EnvVideoPanel)
                        {
                            this._maxScreenPanel = tab.Tag as EnvVideoPanel; // 得到最大化视频窗口

                            if (this._maxScreenPanel.DataContext != null &&
                                this._maxScreenPanel.DataContext is ViewModel_EnvVideoPanel)
                            {
                                ViewModel_EnvVideoPanel vm_EnvVideoPanel = this._maxScreenPanel.DataContext as ViewModel_EnvVideoPanel;
                                vm_EnvVideoPanel.IsMaxPanel = true;
                                vm_EnvVideoPanel.IsRealPlayPanel = Visibility.Visible;
                                vm_EnvVideoPanel.PanelCurrentList = _panelNewCurrentList;
                                vm_EnvVideoPanel.SplitScreen = _splitPanel;
                                vm_EnvVideoPanel.MaxScreen = _maxScreenPanel;
                                vm_EnvVideoPanel.DoubleAction = null;
                                vm_EnvVideoPanel.ChangeBorderColorAction = EnvUtilities.ChangeBorderColor;
                                vm_EnvVideoPanel.ShowMaxScreenAction = EnvUtilities.ShowMaxScreen;
                                vm_EnvVideoPanel.HideMaxScreenAction = EnvUtilities.HideMaxScreen;
                                vm_EnvVideoPanel.StopPanelRealPlayAction = EnvUtilities.StopPanelRealPlay;
                                vm_EnvVideoPanel.RecordVideoAction = EnvUtilities.RecordVideo;
                                vm_EnvVideoPanel.PlayBackAction = EnvUtilities.PlayBack;
                                vm_EnvVideoPanel.ScreenShotAction = EnvUtilities.ScreenShot;
                            }

                            // 获取主界面实际大小，作为最大化视频窗口大小
                            this._maxScreenPanel.Width = ((tab.Tag as EnvVideoPanel).Parent as Panel).ActualWidth;
                            this._maxScreenPanel.Height = ((tab.Tag as EnvVideoPanel).Parent as Panel).ActualHeight;

                            _splitVideoScreen("4"); // 默认 4 分屏
                            _generateNavigation(); // 生成导航栏
                        }
                    }
                    else
                    {
                        throw new Exception("页面初始化失败！");
                    }
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
        }

        #endregion
    }
}
